<?php
class BACKEND_Controller extends CI_Controller {
	public $assigns;
	public function __construct($table = '', $prefix = '',$colid='id')
	{
            parent::__construct();
			$this->table = $table;
			$this->prefix = $prefix;
			$this->colid = $colid;
			$this->privilege = new stdClass();
			$this->assigns = new stdClass();
			$this->assigns->category_types = array(
				array("key"=>"cake","name"=>"BÁNH YÊU"),
				array("key"=>"product","name"=>"MUA BÁN")
			);
            $lang='en';
			$this->lang->load("backend",$lang);
			$this->assigns->langs = $this->lang->lines();
			$this->isAjax = $this->input->is_ajax_request();
			$this->load->model("cms/auth_model");
			$this->checklogin();
			$this->checkaccessdenie();
			$this->backend_model = new Backend_model($this->table,$this->prefix,$this->colid);
	}
	
	function checklogin(){
		
		if($this->input->get_post('action') === "login"){
			$this->onlogin();
		}
		if (!isset($_SESSION["auth"]["user"])) {
			if($this->isAjax){
				$R["result"] = -903;
				$R["message"] = "You must be login.";
				echo json_encode($R);die;
			}else{
				$this->login();
			}
		}
		$this->authority = $_SESSION["auth"]["user"]->ause_authority;
		$this->authoritys = explode(',',$_SESSION["auth"]["user"]->ause_authority);
	}
	function checkaccessdenie(){
		if (!$this->privilege_view()){
			if($this->isAjax){
				$R["result"] = -903;
				$R["message"] = "Access id denied.";
				echo json_encode($R);die;
			}else{
				$this->accessdenied();
			}
		}
	}
	function login(){
		if(isset($_GET["state"]) and isset($_SESSION["auth"]["user"])) redirect( $_GET["state"]);
		echo $c=$this->load->view('cms/auth/login',$this->assigns,true);
		die;
	}
	function logout(){
		session_destroy();
		$this->login();
	}
	function accessdenied(){
		echo $c=$this->load->view('cms/auth/accessdenied',$this->assigns,true);
		die;
	}
	function nothing(){}
	function onlogin(){
		$R["result"] = -1;
		$R["message"] = "Access is denied - Request invalid .";
		$_password = $this->input->post("password");
        $_username = $this->input->post("username");
		if ($_password != false && $_username != false) {
			if (!isset($_SESSION["logintry"]))
                $_SESSION["logintry"] = 0;
            $_SESSION["logintry"]++;
            if ($_SESSION["logintry"] > 4) {
                if (!isset($_SESSION["logintrytime"]))
                    $_SESSION["logintrytime"] = time();
                $timedelay = 60 * 15 - (time("now") - $_SESSION["logintrytime"]);
                if ($timedelay <= 0) {
                    $_SESSION["logintry"] = 0;
                    unset($_SESSION["logintrytime"]);
                } else {
                    $p = floor($timedelay / 60);
                    $p = $p > 0 ? "$p minute " : "";
                    $s = $timedelay % 60;
                    $R["result"] = -999;
                    $R["message"] = ("[Access Denied] Sorry, there have been more than 5 failed login<br/>attempts for this account.<br/>
						It is temporarily blocked in 15 minutes.<br/>
						Remaining time : $p$s second.
						");
					echo json_encode($R);die;
                }
            }else{
				$_name = $_username;
				$user = $this->auth_model->getuser("$_username");
				if ($user) {
					if ($user->ause_password != md5($_username . $_password . $user->ause_secretkey)) {
						$_name = $user->ause_name;
						$R["result"] = -906;
						$R["message"] = "Login failed for user '$_name'.";
					}
					if ($user->ause_delete !== null) {
						$R["result"] = -901;
						$R["message"] = "Valid login but user have been deleted.";
					}
					if ($user->ause_status === "true") {
						unset($user->ause_password);
						//unset($user->ause_salt);
						//unset($user->ause_secretkey);
						$_SESSION["auth"]["user"] = $user;
						$this->authoritys = explode(',',$user->ause_authority);
						$privileges = array();
						$_SESSION["auth"]["privileges"] = $privileges;
						@$this->fileverify();
						$R["result"] = 1;
						$R["message"] = "Valid login.";
						$_SESSION["logintry"] = 0;
					} else {
						$R["result"] = -902;
						$R["message"] = "Valid login but user is not active.";
					}
				} else {
					$R["result"] = -904;
					$R["message"] = "User does't exist or invalid user.";
				}
			}
		}
		echo json_encode($R);die;
	}
	private function fileverify() {
        unset($_SESSION['KCFINDER']);
        if (
                //in_array('Administrator',$this->authoritys) ||
                //strpos(",$this->authority,",',Admin,')!==false ||
                //strpos(",$this->authority,",',User,')!==false ||
				//strpos(",$this->authority,",',FM,')!==false
				!!array_intersect(array('Administrator','Admin','User'),$this->authoritys)
        ) {
            $_SESSION['KCFINDER']['disabled'] = false;
            $_SESSION['KCFINDER']['uploadURL'] = ('/data');
            $_SESSION['KCFINDER']['uploadDir'] = '../../data';
			$files = array(
				'upload' => true,
				'delete' => true,
				'copy' => true,
				'move' => true,
				'rename' => true
			);
			$dirs = array(
				'create' => true,
				'delete' => true,
				'rename' => true
			);
        } elseif (
			//strpos(",$this->authority,",',View,')!==false
			!!array_intersect(array('View'),$this->authoritys)
			) {
            $_SESSION['KCFINDER']['uploadURL'] = ('/data'); //base_url("data");
            $_SESSION['KCFINDER']['uploadDir'] = '../../data';
            $_SESSION['KCFINDER']['disabled'] = false;
            
                $files = array(
                    'upload' => false,
                    'delete' => false,
                    'copy' => false,
                    'move' => false,
                    'rename' => false
                );
                $dirs = array(
                    'create' => false,
                    'delete' => false,
                    'rename' => false
                );
            
        } else {
            $_SESSION['KCFINDER']['uploadURL'] = base_url('data'); //base_url("data");
            $_SESSION['KCFINDER']['uploadDir'] = '../../data';
            $_SESSION['KCFINDER']['disabled'] = true;
            $files = array(
                'upload' => false,
                'delete' => false,
                'copy' => false,
                'move' => false,
                'rename' => false
            );
            $dirs = array(
                'create' => false,
                'delete' => false,
                'rename' => false
            );
            
        }
        $_SESSION['KCFINDER']['access']=array(
                    'files' => $files,
                    'dirs' => $dirs
        );
        
    }
	
	protected function privilege(){
		$this->privilege->aupr_permission = 0;
		if (
                //strpos(",$this->authority,",',Administrator,')!==false ||
                //strpos(",$this->authority,",',Admin,')!==false ||
                //strpos(",$this->authority,",',User,')!==false
				!!array_intersect(array('Administrator','Admin','User'),$this->authoritys)
        ){
			$this->privilege->aupr_permission = 777;
			return true;
		}
		return false;
	}
	protected function privilege_view(){
		$this->privilege->aupr_permission = 0;
		if (
                //strpos(",$this->authority,",',View,')!==false 
				!!array_intersect(array('View'),$this->authoritys)
        ){
			$this->privilege->aupr_permission = 755;
			return true;
		}
		if (
                //strpos(",$this->authority,",',Administrator,')!==false ||
                //strpos(",$this->authority,",',Admin,')!==false ||
                //strpos(",$this->authority,",',User,')!==false 
				!!array_intersect(array('Administrator','Admin','User'),$this->authoritys)
        ){
			$this->privilege->aupr_permission = 777;
			return true;
		}
		return false;
	}
	protected function beforeinsert(){}
	protected function beforeupdate(){}
	protected function beforecommit(){}
	protected function beforedelete(){}
	function oncommit(){
		$this->beforecommit();
		$R["result"] = -1;
        $R["message"] = ascii_to_entities("This function to requires an administrative account.<br/>Please check your authority, and try again.");
        if ($this->privilege()) {
            $Params = $this->input->get_post('Params');
			if(!empty($Params)){
				$Id = (int) $this->input->post('Id');
				if ($Id != 0) {
					$record=$this->backend_model->onGet($Id);
					if($record){
						$rs = $this->backend_model->onUpdate($Id, $Params);
					}else{
						$R["result"] = -203;
						$R["message"] = "Record doesn't exist.";
						echo (json_encode($R));
						return;
					}
				} else {
					$rs = $this->backend_model->onInsert($Params);
					if ($rs === true)
						$R['last_id'] = $this->backend_model->_get_last_insert_id();
				}
				if ($rs === true) {
					$R["result"] = 1;
					$R["message"] = ("Success. Data have been save.");
				} else {
					$R["result"] = -1;
					$R["error_number"] = $this->backend_model->db->_error_number();
					$R["error_message"] = $this->backend_model->db->_error_message();
					$R["last_query"] = $this->backend_model->db->last_query();
					$R["message"] = ("System rejected your data.<br/>Please check data input and try again.<br/>");
					if ($R["error_number"] != 0){
						$R["message"].=("<span class='erc'>[" . $R["error_number"] . "] " . $R["error_message"] . ".</span>");
					}
				}
			}else $R["message"] = "Data invalid.";
        }
        echo (json_encode($R));
	}
	function oninsert(){
		$this->beforeinsert();
	}
	function onupdate(){
		$this->beforeupdate();
	}
	function ondelete(){
		$this->beforedelete();
        $R["result"] = -1;
        $R["message"] = ("This function to requires an administrative account.<br/>Please check your authority, and try again.");
        if ($this->privilege()) {
            $id = (int) $this->input->post('Id');
            if ($id > 0) {
                $tmp = $this->backend_model->onGet($id);
                if ($tmp) {
                    if (
                            (
								isset($tmp->{$this->prefix . "lock"}) &&
								(!empty($tmp->{$this->prefix . "lock"}))
							) ||
                            (
								isset($tmp->{$this->prefix . "Lock"}) &&
								(!empty($tmp->{$this->prefix . "Lock"}))
							)
                    ) {
                        $R["message"] = ("Can't delete 'System' record. Record have been locked.");
                    } else {$rs=false;
                        $rs = $this->backend_model->onDelete($id);
                        if ($rs === true) {
                            $R["result"] = 1;
                            $R["message"] = ("Success. Record have been deleted.");
                        } else {
                            $R["result"] = -1;
                            $R["error_number"] = $this->backend_model->db->_error_number();
                            $R["error_message"] = $this->backend_model->db->_error_message();
                            $R["message"] = ("Fail. Please check data input and try again.<br/>");
                            if ($R["error_number"] != 0)
                                $R["message"].=("<span class='erc'>[" . $R["error_number"] . "] " . $R["error_message"] . ".</span>");
                        }
                    }
					//$R["message"] = ($tmp->{$this->prefix . "lock"});
                }else {
                    $R["message"] = ("Record does't exist.");
                }
            } else {
                $R["message"] = ("Id invalid.");
            }
        }
        $this->output->set_header('Content-type: application/json');
        $this->output->set_output(json_encode($R));
	}
	
	function bindingdata(){
		//$this->backend_model = new Backend_model($this->table,$this->prefix,$this->colid);
		$result = $this->backend_model->_bindingdata();
		$this->output->set_header('Content-type: application/json');
        $this->output->set_output(json_encode($result));
	}
	
}
include 'SO_Controller.php';
include 'CP_Controller.php';
include 'CO_Controller.php';
include 'GM_Controller.php';
include 'GO_Controller.php';
include 'EP_Controller.php';
include 'SM_Controller.php';
#include 'Frontend_Controller.php';